<script lang="ts" setup>
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import ArticleApi, {
  ArticleEditRequest,
  ArticleType
} from "@/api/articles/article";

import { ComStatus } from "@/api/model";
import { handleTree } from "@/utils/tree";
import CategoryApi from "@/api/articles/articleCategory";
import { message } from "@/utils/message";
import {
  ElButton,
  ElForm,
  ElFormItem,
  ElInput,
  FormInstance,
  FormRules
} from "element-plus";
import { onBeforeUnmount, onMounted, shallowRef } from "vue";
import { ref, Ref, reactive } from "vue";
import { useRoute } from "vue-router";
import { IDomEditor, IEditorConfig, IToolbarConfig } from "@wangeditor/editor";
import { http } from "@/utils/http";

export interface Props {
  modelValue: boolean;
  readonly id: number | null;
}
const route = useRoute();
const treeData = ref([]);
const defaultPostInfo: ArticleEditRequest = {
  id: 0,
  title: "",
  slug: "",
  summary: "",
  content: "",
  categoryId: 0,
  status: ComStatus.Enabled,
  type: ArticleType.Article
};

const postInfo: Ref<ArticleEditRequest> = ref(defaultPostInfo);
onMounted(async () => {
  const postId = route.query?.id as string;
  if (postId != null) {
    getPostInfo(parseInt(postId));
  }
  await loadTree();
});
async function getPostInfo(id: number) {
  if (route.query.id) {
    const postDetail = await ArticleApi.getInfo(id);
    postInfo.value = { ...postDetail };
  } else {
    postInfo.value = { ...defaultPostInfo };
  }
}
const loading = ref(true);
async function loadTree() {
  loading.value = true;
  const data = await CategoryApi.list({ keyword: null });
  treeData.value = handleTree(data);
  setTimeout(() => {
    loading.value = false;
  }, 100);
}

const formRef = ref<FormInstance>();
const rules = reactive<FormRules>({
  title: [{ required: true, message: "请输入标题" }]
});
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async valid => {
    if (valid) {
      await ArticleApi.edit({
        ...postInfo.value
      });
      message("修改成功", { type: "success" });
    } else {
      return false;
    }
  });
};

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();
const toolbarConfig: Partial<IToolbarConfig> = {
  excludeKeys: ["fullScreen"]
};
type InsertFnType = (url: string, alt?: string, href?: string) => void;
const editorConfig: Partial<IEditorConfig> = {
  placeholder: "请输入内容...",
  MENU_CONF: {
    uploadImage: {
      server: "api/common/upload/image",
      // 自定义插入图片
      async customUpload(file: File, insertFn: InsertFnType) {
        const param = new FormData(); // 创建form对象
        //注意files是对应后台的参数名哦
        param.append("file", file);
        const res = await http.request({
          url: "/api/common/upload/image",
          method: "post",
          headers: { "Content-Type": "multipart/form-data" },
          data: param
        });
        insertFn(res as string);
      }
    }
  }
};
const handleCreated = (editor: IDomEditor) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};

const mode = "simple";
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});
</script>
<template>
  <div class="main">
    <el-form
      ref="formRef"
      :model="postInfo"
      label-width="100px"
      class="demo-ruleForm"
      :rules="rules"
    >
      <el-form-item label="标题" prop="title">
        <el-input v-model="postInfo.title" type="textarea" />
      </el-form-item>
      <el-form-item label="分类">
        <el-tree-select
          :data="treeData"
          v-model="postInfo.categoryId"
          default-expand-all
          check-strictly
          :props="{
            value: 'id',
            label: 'name',
            emitPath: false
          }"
          clearable
        />
      </el-form-item>
      <el-form-item label="类型">
        <el-radio-group v-model="postInfo.type">
          <el-radio-button :label="1">文章</el-radio-button>
          <el-radio-button :label="2">公告</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="状态">
        <x-status v-model="postInfo.status" enableText="已发布" />
      </el-form-item>
      <el-form-item label="封面图">
        <x-image v-model="postInfo.slug" />
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <div class="wangeditor">
          <Toolbar
            style="border-bottom: 1px solid #ccc"
            :editor="editorRef"
            :defaultConfig="toolbarConfig"
            :mode="mode"
          />
          <Editor
            style="height: 500px; overflow-y: hidden"
            v-model="postInfo.content"
            :defaultConfig="editorConfig"
            :mode="mode"
            @onCreated="handleCreated"
          />
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(formRef)">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
